<template>
  <view class="the-charts" :style="{'background': isOnlyTop ? 'transparent' : '#EEF4F5'}">
    <template v-if="!isOnlyTop">
      <view class="bg-ph" v-if="state.groupList.length > 0"></view>
      <view class="charts-header">
        <!-- <image class="icon-ph" src="../static/icon-ph.png"></image> -->
        <ul class="tab-box">
          <li :class="['tab-item', {'tab-active': state.tabActive.value === index}]" v-for="(item, index) in state.tabList" :key="index" @tap="handleTabItem(item)">
            <text>{{item.name}}</text>
          </li>
        </ul>
        <view class="flesh-box" v-if="state.groupList.length > 0" @tap="onGetGroupRank(useGroupData?.groupType || 0)">
          <text>刷新</text>
          <image src="../../static/huanyihuan.png"></image>
        </view>
      </view>
      <view v-if="state.tabActive.rankType == 2" class="thums-tip">每人每天可点赞5次，点赞榜前三的跑团可获得超级大奖</view>
    </template>
    <view class="top-box" v-if="state.allGroupList.length > 0">
      <view class="item-box">
        <view class="top-item top-item2" @tap="gotoGroupDetail(state.allGroupList[1])">
          <text :class="['text-item',state.allGroupList[1] && state.myGroup?.groupId === state.allGroupList[1].groupId?'text-active':'']">TOP 2</text>
          <view class="group-avart-active" :style="{border: state.allGroupList[1] && state.myGroup?.groupId === state.allGroupList[1].groupId ? '2px solid #2DE588' : 'none'}">
            <image class="group-avart" :src="(state.allGroupList[1] && state.allGroupList[1].groupHeadImage) ? state.allGroupList[1].groupHeadImage : '../static/rank-top2.png'"></image>
          </view>
          <view class="top-bg top-bg2">
            <template v-if="state.allGroupList.length > 1">
              <view class="top-name">{{state.allGroupList[1].groupName}}</view>
              <view class="top-distance">{{state.allGroupList[1].totalDistance}}公里</view>
            </template>
            <view class="no-data" v-else>暂无</view>
          </view>
        </view>
        <view class="thumbs-box" @click.stop="onCreateThumsUp(state.allGroupList[1])">
          <view class="like-ph">
            <image class="icon-like" :src="!state.allGroupList[1]?.isLike ? likeDefault : likeActive"></image>
            <view :animation="state.animationData[state.allGroupList[1]?.groupId]" class="praise-me animation-opacity" >+1</view>
          </view>
          <text class="num-like">{{state.allGroupList[1]?.likeNumber > 9999 ? "1万+" : (state.allGroupList[1]?.likeNumber || 0)}}</text>
        </view>
      </view>
      <view class="item-box">
        <view class="top-item top-item1" @tap="gotoGroupDetail(state.allGroupList[0])">
          <text :class="['text-item',state.allGroupList[0] && state.myGroup?.groupId === state.allGroupList[0].groupId?'text-active':'']">TOP 1</text>
          <view class="group-avart-active" :style="{border: state.allGroupList[0] && state.myGroup?.groupId === state.allGroupList[0].groupId ? '2px solid #2DE588' : 'none'}">
            <image class="group-avart" :src="state.allGroupList[0] && state.allGroupList[0].groupHeadImage"></image>
          </view>
          <view class="top-bg top-bg1">
            <view class="top-name" v-if="state.allGroupList[0]">{{state.allGroupList[0].groupName}}</view>
            <view class="top-distance" v-if="state.allGroupList[0]">{{state.allGroupList[0].totalDistance}}公里</view>
            <view class="no-data" v-if="!state.allGroupList[0]">暂无</view>
          </view>
        </view>
        <view class="thumbs-box" @click.stop="onCreateThumsUp(state.allGroupList[0])">
          <view class="like-ph">
            <image class="icon-like" :src="!state.allGroupList[0]?.isLike ? likeDefault : likeActive"></image>
            <view :animation="state.animationData[state.allGroupList[0]?.groupId]" class="praise-me animation-opacity" >+1</view>
          </view>
          <text class="num-like">{{ state.allGroupList[0]?.likeNumber > 9999 ? "1万+" : (state.allGroupList[0]?.likeNumber || 0) }}</text>
        </view>
      </view>
      <view class="item-box">
        <view class="top-item top-item3" @tap="gotoGroupDetail(state.allGroupList[2])">
          <text :class="['text-item',state.allGroupList[2] && state.myGroup?.groupId === state.allGroupList[2].groupId?'text-active':'']">TOP 3</text>
          <view class="group-avart-active" :style="{border: state.allGroupList[2] && state.myGroup?.groupId === state.allGroupList[2].groupId ? '2px solid #2DE588' : 'none'}">
            <image class="group-avart" :src="(state.allGroupList[2] && state.allGroupList[2].groupHeadImage) ? state.allGroupList[2].groupHeadImage : '../static/rank-top3.png'"></image>
          </view>
          <view class="top-bg top-bg3">
            <template v-if="state.allGroupList.length > 2">
              <view class="top-name">{{state.allGroupList[2].groupName}}</view>
              <view class="top-distance">{{state.allGroupList[2].totalDistance}}公里</view>
            </template>
            <view class="no-data" v-else>暂无</view>
          </view>
        </view>
        <view class="thumbs-box" @click.stop="onCreateThumsUp(state.allGroupList[2])">
          <view class="like-ph">
            <image class="icon-like" :src="!state.allGroupList[2]?.isLike ? likeDefault : likeActive"></image>
            <view :animation="state.animationData[state.allGroupList[2]?.groupId]" class="praise-me animation-opacity" >+1</view>
          </view>
          <text class="num-like">{{state.allGroupList[2]?.likeNumber > 9999 ? "1万+" : (state.allGroupList[2]?.likeNumber || 0)}}</text>
        </view>
      </view>
    </view>
    <template v-if="!isOnlyTop">
      <view class="group-ph" v-if="state.groupList.length > 0">
        <template v-for="(item, index) in state.groupList" :key="index">
          <view v-if="item.rank>3" :class="['item-ph', {'item-ph-me': state.myGroup?.groupId === item.groupId}]"  :key="index" @tap="gotoGroupDetail(item)">
            <view class="ph-inner">
              <view class="group-con">
                <view class="ranking">{{item.rank > 9 ? item.rank : `0${item.rank}`}}</view>
                <image class="group-avart" :src="item.groupHeadImage"></image>
                <view class="group-name">{{item.groupName}}</view>
              </view>
              <view class="group-distance">
                <view class="distance-txt">{{item.totalDistance}}公里</view>
                <view class="thumsup-box">
                  <text>|</text>
                    <view class="like-con" @click.stop="onCreateThumsUp(item)">
                      <image class="icon-like" :src="!item.isLike ? phLikeDefault : phLikeActive"></image>
                      <view :animation="state.animationData[item.groupId]" class="praise-me animation-opacity">+1</view>
                    </view>
                    <text class="num-like">{{item.likeNumber > 9999 ? "1万+" : (item.likeNumber || 0)}}</text>
                  </view>
                </view>
            </view>
            <view class="ranking-txt" v-if="item.rank > 3 && state.myGroup?.groupId === item.groupId">
              你的团队距离第3名还差{{state.tabActive.rankType == 1 ? `${state.meDistance}公里` : `${state.meDistance}个点赞`}}，奋起直追吧！
            </view>
          </view>
        </template>
        <view v-if="(!state.isMore && state.myGroup?.rank > 6) || (state.isMore && state.myGroup?.rank > 30)" class="item-ph item-ph-me" @tap="gotoGroupDetail(item)">
          <view class="ph-inner">
            <view class="group-con">
              <view class="ranking">{{state.myGroup?.rank>9?state.myGroup?.rank:`0${state.myGroup?.rank}`}}</view>
              <image class="group-avart" :src="state.myGroup?.groupHeadImage"></image>
              <view class="group-name">{{state.myGroup?.groupName}}</view>
            </view>
            <view class="group-distance">
              <text>{{state.myGroup?.totalDistance}}公里</text>
              <view class="thumsup-box">
                <text>|</text>
                <view class="like-con" @click.stop="onCreateThumsUp(state.myGroup)">
                  <image class="icon-like" :src="!state.myGroup?.isLike ? phLikeDefault : phLikeActive"></image>
                  <view :animation="state.animationData[state.myGroup?.groupId]" class="praise-me animation-opacity">+1</view>
                </view>
                <text class="num-like">{{state.myGroup?.likeNumber > 9999 ? "1万+" : (state.myGroup?.likeNumber || 0)}}</text>
              </view>
            </view>
          </view>
          <view class="ranking-txt">
            你的团队距离第3名还差{{state.tabActive.rankType == 1 ? `${state.meDistance}公里` : `${state.meDistance}点赞`}}，奋起直追吧！
          </view>
        </view>
      </view>
      <view v-if="state.allGroupList?.length >= 3 && state.allGroupList?.length<=7" @tap="handleMore">
        <view class="more-box">
          <text>暂无其他团队</text>
        </view>
      </view>
      <view v-if="state.allGroupList?.length > 6" @tap="handleMore">
        <view class="more-box" v-if="!state.isMore">
          <text>查看全部</text>
          <image src="../static/icon-arrow-bottom.png"></image>
        </view>
        <view class="more-box" v-else>
          <text>查看收起</text>
          <image src="../static/icon-arrow-top.png"></image>
        </view>
      </view>
    </template>
    <view class="no-data" v-if="state.allGroupList?.length == 0">
      <image class="no-rank" src="../static/no-rank.png"></image>
			<view>暂无排名信息</view>
		</view>
  </view>
</template>

<script setup name="BottomDrawer">
import { onLoad, onShow, onHide, onUnload } from "@dcloudio/uni-app";
import { reactive, ref, toRefs, watch, onMounted, getCurrentInstance, defineEmits } from 'vue';
import * as API from "../../api/api"
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useGroupStore } from "../../store/group"
import { userLoginStore } from "../../store/userLogin";
import likeDefault from "../static/icon-like-default.png"
import likeActive from "../static/icon-like-active.png"
import phLikeDefault from "../static/ph-like-default.png"
import phLikeActive from "../static/ph-like-active.png"
const useGroupData = useGroupStore()
const useRunInfoData = useRunInfoStore()
const userLoginData = userLoginStore()
const { proportionShow, initStatus, timerNum, centerDistance, runType } = storeToRefs(useRunInfoData)
const appInstance = getCurrentInstance().proxy
const props = defineProps({
  isOnlyTop: {
    type: Boolean,
    default: false
  },
  isChangeGroup: {
    type: Boolean,
    default: false
  }
})

const { isOnlyTop, isChangeGroup }  = toRefs(props)

const state = reactive({
  tabActive: {
    name: "里程榜",
    value: 0,
    rankType: 1
  },
  tabList: [
    {
      name: "里程榜",
      value: 0,
      rankType: 1
    },
    {
      name: "｜",
      value: 1
    },
    {
      name: "点赞榜",
      value: 2,
      rankType: 2
    },
  ],
	myGroup: [],
	groupList: [],
	isMore: false,
  allGroupList: [],
	meDistance: 0,
  animationData: {},
  userInfo: null,
  token: null,
  isClickFlag: true
})
const emits = defineEmits(["thumsUpCallBack"])
const alertDialogRef = ref(null)

const handleTabItem = (item, index) => {
  if (index == 1) return
  state.tabActive = item
  onGetGroupRank()
}

const onCreateThumsUp = (groupInfo) => {
  if (!state.isClickFlag) return
  state.isClickFlag = false
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (!state.token) {
    uni.showToast({
      title: "请先登录，再点赞",
      icon: "none"
    })
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/login/login"
      })
      userLoginData.setRedirectUrl(currentPage.$page.fullPath)
      state.isClickFlag = true
    }, 1500)
    return
  }
  if (!groupInfo || !groupInfo.groupId) {
    state.isClickFlag = true
    return
  }
  useGroupData.onThumsUp(groupInfo.groupId).then(res => {
    state.isClickFlag = true
    if (res.code === 0) {
      onPraise(groupInfo)
      if (currentPage.route.includes("runGroupPages/index/index")) {
        emits("thumsUpCallBack")
      } else {
        onGetGroupRank()
      }      
    }
  }).catch(err => {
    state.isClickFlag = true
  })
}

const gotoGroupDetail = (item) => {
  if (!item?.groupId) return
  uni.navigateTo({
    url: `/runGroupPages/myGroup/index?groupId=${item.groupId}`,
  });
}

//点赞
const onPraise = (item) => {
  const id = item.groupId
  //点击时，描绘动画的运动过程
  state.animation.translateY(-80).opacity(1).step({duration: 800});
  state.animationData = {};  //必须要清空，如果没有清空，引用是一样的，页面就不会重新渲染，导致动画无法显示。vue的特性
  state.animationData[id] = state.animation.export();  //导出动画，对应的键是当前数据的ID
  setTimeout(()=>{  //时间到后，动画恢复原点
    state.animation.translateY(0).opacity(0).step({duration: 0})
    state.animationData = {};
    state.animationData[id] = state.animation.export();
  },500);
}

const handleMore = () => {
	state.isMore = !state.isMore
	if (state.isMore) {
		state.groupList = state.allGroupList.slice(3, 30)
	} else {
    if (state.myGroup) {
      if (state.myGroup.rank > 6) {
        state.groupList = state.allGroupList.slice(3, 5)
      } else {
        state.groupList = state.allGroupList.slice(3, 6)
      }
    } else {
      state.groupList = state.allGroupList.slice(3, 6)
    }
	}
}

const onGetGroupRank = (groupType) => {
  uni.showLoading({
    title: "加载中...",
    icon: "none"
  })
  console.log("排行榜", groupType || groupType === 0, groupType, useGroupData.groupType)
	state.isMore = false
	let params = {
		groupId: useGroupData?.myGroupInfo?.groupId,
    userId: state.userInfo?.customers?.customerId,
    groupType: (groupType || groupType === 0)  ? Number(groupType) : Number(useGroupData.groupType), 
    rankType: state.tabActive.rankType
	}
	API.getGroupRank(params).then(res => {
    uni.hideLoading()
		if (res.code == 0) {
			state.allGroupList = res.data.groupList
			state.groupList = state.allGroupList.slice(3, 6)
			state.myGroup = res.data.myGroup
      if (res.data.myGroup) {
        if (res.data.myGroup.rank > 6) {
          state.groupList = state.allGroupList.slice(3, 5)
        }
      }
			if (state.myGroup.rank > 3) {
        if (state.tabActive.rankType == 1) {
          state.meDistance = (state.allGroupList[2].totalDistance - state.myGroup.totalDistance).toFixed(2)
        } else {
          state.meDistance = state.allGroupList[2].likeNumber - Number(state.myGroup.likeNumber)
        }
			}
		}
	}).catch(err => {
    uni.hideLoading()
	})
}

onLoad(() => {
 	//页面加载时创建一个动画
  state.animation = uni.createAnimation();
  state.isClickFlag = true
})

onShow(() => {
  state.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
	state.token = uni.getStorageSync("token") ? uni.getStorageSync("token") : null
})

watch(() => isChangeGroup.value, (newValue, oldValue) => {
  state.tabActive = {
    name: "里程榜",
    value: 0,
    rankType: 1
  }
}, {imediate: true})

defineExpose({
  onGetGroupRank
})

</script>

<style lang="scss">
  .the-charts{
    padding-bottom: 24rpx;
    // height: 868rpx;
    background: #EEF4F5;
    border-radius: 24rpx;
    box-sizing: border-box;
    margin-top:24rpx;
    position: relative;
    .bg-ph{
      width: 586rpx;
      height: 256rpx;
      background: url('https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/bg-ph.png') 0 0 no-repeat;
      background-size: 100% 100%;
      position: absolute;
      left: 36rpx;
      top: 150rpx;
    }
    .charts-header{
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
      padding-bottom: 94rpx;
      .tab-box{
        width: 266rpx;
        display: flex;
        justify-content: space-around;
        align-items: center;
        position: absolute;
        left: 50%;
        top: 24rpx;
        transform: translateX(-50%);
        .tab-item{
          font-size: 36rpx;
          color: rgba(34,34,34,0.7);
          text{
            position: relative;
            z-index: 2;
          }
          &:nth-child(2){
            color: #D2DAD8;
          }
        }
        .tab-active{
          font-weight: 600;
          font-size: 36rpx;
          color: #222222;
          position: relative;
          &::after{
            width: 112rpx;
            height: 32rpx;
            content: "";
            background: url("https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/tab-active.png") 0 0 no-repeat;
            background-size: 100% 100%;
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }
      .icon-ph{
        width: 108rpx;
        height: 40rpx;
      }
      .flesh-box{
        display: flex;
        align-items: center;
        position: absolute;
        right: 24rpx;
        top: 24rpx;
        text{
          font-size: 28rpx;
          color: #595858;
          margin-right: 12rpx;
        }
        image{
          width: 24rpx;
          height: 28rpx;
        }
      }
    }
    .thums-tip{
      width: 532rpx;
      padding: 10rpx 20rpx;
      font-size: 20rpx;
      background: #E2E9EB;
      color: rgba(34,34,34,0.6);
      margin: 0 auto;
      border-radius: 28rpx;
      box-sizing: border-box;
    }
    .top-box{
      display: flex;
      justify-content: space-between;
      margin: 0 24rpx;
      .thumbs-box{
        display: flex;
        justify-content: center;
        align-items: flex-start;
        image{
          width: 32rpx;
          height: 32rpx;
        }
        text{
          margin-left: 6rpx;
          font-size: 28rpx;
          color: rgba(34,34,34,0.7);
        }
        .like-ph{
          position: relative;
        }
      }
      .top-item{
        width: 168rpx;
        height: 260rpx;
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        text{
          display: block;
          width: 168rpx;
          font-family: system-ui;
          font-weight: 900;
          font-size: 36rpx;
          color: #222222;
          line-height: 44rpx;
          text-align: center;
          font-style: italic;
					position: relative;
					z-index: 2;
        }
        image{
          width: 92rpx;
          height: 92rpx;
          background: #66B2FF;
          border-radius: 100%;
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);
					z-index: 1;
        }
        .text-active{
          background-image:linear-gradient(81.48680304106813deg, #3BFF29 0%, #1CC5FF 100%);;
          -webkit-background-clip:text;
          -webkit-text-fill-color:transparent;
        }
        .top-bg{
          width: 168rpx;
          height: 172rpx;
          position: absolute;
          left: 0;
          bottom: 10rpx;
          font-size: 24rpx;
          .top-name{
						width: 168rpx;
            text-align: center;
            margin-top: 60rpx;
            color: #222222;
						overflow: hidden; /* 确保超出容器的文本被裁剪 */
						white-space: nowrap; /* 确保文本在一行内显示 */
						text-overflow: ellipsis; /* 使用省略号表示文本超出 */
          }
          .top-distance{
            text-align: center;
            color: rgba(34,34,34,0.7);
            margin-top: 4rpx;
          }
        }
        .top-bg1{
          background: url('https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/top1.png') 0 0 no-repeat;
          background-size: 100% 100%;
        }
        .top-bg2{
          background: url('https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/top2.png') 0 0 no-repeat;
          background-size: 100% 100%;
        }
        .top-bg3{
          background: url('https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/top3.png') 0 0 no-repeat;
          background-size: 100% 100%;
        }
      }
      .top-item1{
        margin-top: 10rpx;
      }
      .top-item2, .top-item3{
        margin-top: 47rpx;
      }
    }
		.group-avart-active{
			width: 104rpx;
			height: 104rpx;
			border-radius: 100%;
			position: relative;
			z-index: 1;
			margin-top: -17rpx;
		}
    .group-ph{
      margin-top: 10rpx;
      position: relative;
      .item-ph{
        font-family: PingFangSC, PingFang SC;
        padding: 16rpx 0;
        .ph-inner{
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-left: 24rpx;
          .group-con{
            display: flex;
            align-items: center;
            .ranking{
							width: 30rpx;
							font-family: ArialMT;
              font-weight: 500;
              font-size: 32rpx
            }
            image{
              width: 60rpx;
              height: 60rpx;
              border-radius: 100%;
              margin: 0 8rpx 0 16rpx;
							flex-shrink: 0;
            }
            .group-name{
							width: 200rpx;
              font-size: 28rpx;
              color: #222222;
							overflow: hidden; /* 确保超出容器的文本被裁剪 */
							white-space: nowrap; /* 确保文本在一行内显示 */
							text-overflow: ellipsis; /* 使用省略号表示文本超出 */
            }
          }
          .group-distance{
						flex-shrink: 0;
            font-size: 28rpx;
            color: rgba(34,34,34,0.7);
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-family: PingFangSC, PingFang SC;
            box-sizing: border-box;
            .distance-txt {
              width: 170rpx;
              text-align: right;
              flex-shrink: 0;
            }
            .thumsup-box{
              width: 150rpx;
              display: flex;
              align-items: center;
              text:nth-child(1) {
                padding: 0 16rpx;
              }
            }
            .like-con{
              display: flex;
              align-items: center;
              font-size: 28rpx;
              color: rgba(34,34,34,0.7);
              position: relative;
              image{
                width: 30rpx;
                height: 30rpx;
              }
            }
            .num-like{
              margin-left: 8rpx;
            }
          }
        }
        .ranking-txt{
          font-size: 22rpx;
          color: rgba(34,34,34,0.7);
          margin: 12rpx 0 0 56rpx;
        }
      }
      .item-ph-me{
        background: linear-gradient( 172deg, #E6FFF2 0%, #FFFFFF 100%);
        box-shadow: 0rpx 4rpx 12rpx -4rpx #DBE3E4;
      }
    }
    .more-box{
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 16rpx auto;
      font-size: 24rpx;
      color: rgba(34,34,34,0.6);
      image{
        width: 28rpx;
        height: 28rpx;
        margin-left: 8rpx;
      }
    }
  }
	.no-data{
		text-align: center;
		padding-top: 70rpx;
    .no-rank{
      width: 244rpx;
      height: 160rpx;
    }
    view{
      font-size: 32rpx;
      color: rgba(34,34,34,0.75);
      padding-bottom: 50rpx;
    }
	}
  .praise-me {
    font-size: 44rpx;
    color: #FFA31E;
    align-self: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .animation-opacity{
    font-weight: bold;
    color: #FFA31E;
    opacity: 0;   /* 备注： 默认透明度为 0，不显示 */
  }
</style>
